package com.zzj.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzj.base.Result;
import com.zzj.entity.Hospital;
import com.zzj.entity.PatientAppointment;
import com.zzj.model.dto.QueryListDTO;
import com.zzj.model.dto.appointment.AppointmentCreateDTO;
import com.zzj.service.INurseScheduleService;
import com.zzj.service.IPatientAppointmentService;
import com.zzj.service.RedisService;
import com.zzj.utils.JWTUtil;
import com.zzj.utils.QueryUtil;
import com.zzj.utils.Utils;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-03-01
 */
@RestController
@RequestMapping("/appointment")
public class PatientAppointmentController {

    @Resource
    private IPatientAppointmentService appointmentService;
    @Resource
    private INurseScheduleService nurseScheduleService;

    @Resource
    private RedisService redisService;

    @Transactional
    @PostMapping("list")
    public Result list(@RequestBody @Validated QueryListDTO in) {
        QueryWrapper<PatientAppointment> queryWrapper = QueryUtil.paramsWrapper(in.getAndParams(), in.getOrParams(), in.getOrderParams());
        Page<PatientAppointment> patientAppointmentPage = new Page<>(in.getPageNo(), in.getPageSize());
        IPage<PatientAppointment> patientAppointmentIPage = appointmentService.getBaseMapper().selectPage(patientAppointmentPage, queryWrapper);
        return Result.success(patientAppointmentIPage);
    }

    @Transactional
    @PostMapping("create")
    public Result create(@RequestBody @Validated AppointmentCreateDTO in) {
        PatientAppointment appointment = JSONObject.parseObject(JSON.toJSONString(in), PatientAppointment.class);
        appointmentService.save(appointment);
        //预约后添加到redis
        String username = appointment.getPatientUsername();

        String scheduleId = redisService.getBookScheduleId(username);
        if (scheduleId == null) {
            scheduleId = "";
        }
        redisService.setBookScheduleId(username, scheduleId+appointment.getScheduleId() + ",");
        nurseScheduleService.book(in.getScheduleId());

        Result result = redisService.verifyVerificationCode(in.getEmail(), String.valueOf(in.getCode()));
        if (result.getCode() != 0) {
            return result;
        }

        return Result.success("预约成功");
    }

    /**
     * 取消
     *
     * @param token
     * @param appointmentId
     * @param scheduleId
     * @return
     */
    @Transactional
    @PostMapping("cancelById")
    public Result cancelById(@RequestHeader(value = "Authorization") String token,
                             @RequestParam int appointmentId,
                             @RequestParam int scheduleId) {
        String username = JWTUtil.getUsername(token);
        String bookScheduleId = redisService.getBookScheduleId(username);

        if (!Utils.stringIsContainStrSplit(String.valueOf(bookScheduleId), String.valueOf(scheduleId), ",")) {
            return Result.success("未预约");
        }
        redisService.setBookScheduleId(username, bookScheduleId.replace(scheduleId + ",", ""));
        appointmentService.setAppointmentStatus(appointmentId, 5);

        nurseScheduleService.cancel(scheduleId);

        return Result.success("取消成功");
    }

    @Transactional
    @PostMapping("id")
    public Result id(@RequestParam int id) {
        PatientAppointment one = appointmentService.getOne(Wrappers.<PatientAppointment>lambdaQuery()
                        .eq(PatientAppointment::getId, id),
                false);
        if (one == null) {
            return Result.error("不存在");
        }
        return Result.success(one);
    }

    /**
     * 开启治疗
     *
     * @param id
     * @return
     */
    @Transactional
    @PostMapping("treat")
    public Result treat(@RequestParam int id) {
        boolean update = appointmentService.setAppointmentStatus(id, 2);
        if (!update) {
            return Result.error("不存在");
        }
        return Result.success();
    }

    /**
     * 完成
     *
     * @param id
     * @return
     */
    @PostMapping("finish")
    public Result finish(@RequestParam int id) {
        boolean update = appointmentService.setAppointmentStatus(id, 4);
        if (!update) {
            return Result.error("不存在");
        }
        return Result.success();
    }
}
